//
//  XHUseTrafficViewController.m
//  umibus
//
//  Created by 冷山 on 16/6/17.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHUseTrafficViewController.h"
#import "XHPaymentBouncedViewController.h"
#import "XHTrafficPackageViewController.h"
#import "XHTabBarController.h"
#import "XHEditorPassWordViewController.h"

#import "XHTrafficUserCell.h"
#import "XHTrafficUserDetailCell.h"
#import "XHTrafficUserNumberCell.h"

#import "Services.h"
#import "AppDelegate.h"

#import <AddressBookUI/AddressBookUI.h>
#import <ContactsUI/ContactsUI.h>

#define kPhoneNumberKey 3

@interface XHUseTrafficViewController ()<XHTrafficUserDetailCellDelegate,XHTrafficUserNumberCellDelegate,ABPeoplePickerNavigationControllerDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *ui_tableView;
@property (copy, nonatomic) NSString *m_inputMobile;
@property (strong, nonatomic) NSString * operatorName;
@property (copy, nonatomic) NSString *m_submitToken;
@property (strong, nonatomic) NSString * conut;
@property (strong, nonatomic) NSString * phoneLocation;

@end

@implementation XHUseTrafficViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHTrafficUserCell" bundle:nil] forCellReuseIdentifier:XHTrafficUserCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHTrafficUserDetailCell" bundle:nil] forCellReuseIdentifier:XHTrafficUserDetailCellIdentifier];
    [self.ui_tableView registerNib:[UINib nibWithNibName:@"XHTrafficUserNumberCell" bundle:nil] forCellReuseIdentifier:XHTrafficUserNumberCellIdentifier];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(popToViewController) name:@"popToViewController" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(editorPassWord) name:@"editorPassWordViewController" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangesNotification:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)editorPassWord
{
    XHEditorPassWordViewController * viewController = [[XHEditorPassWordViewController alloc]init];
    viewController.title = @"修改密码";
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)popToViewController
{
    NSArray * viewControllerArray = self.navigationController.viewControllers;
    for (UIViewController * vc in viewControllerArray)
    {
        if ([vc isKindOfClass:[XHTrafficPackageViewController class]])
        {
            [self.navigationController popToViewController:vc animated:YES];
        }
    }
}

- (void)getOperatorInfoWithMobile:(NSString*)mobile
{
    [ServiceManager getOperatorInfoWithMobile:mobile success:^(NSDictionary *data) {
        self.operatorName = data[@"operatorName"];
        self.phoneLocation = data[@"provinceID"];
        [self.ui_tableView reloadData];
    } failure:^(NSDictionary *data) {
        
    }];
}

- (void)setM_inputMobile:(NSString *)m_inputMobile{
    m_inputMobile=[m_inputMobile stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"- "];
    m_inputMobile = [[m_inputMobile componentsSeparatedByCharactersInSet: doNotWant]componentsJoinedByString:@""];
//    if ([NSString checkPhoneString:m_inputMobile]) {
        if (![m_inputMobile isEqualToString:_m_inputMobile]) {
            _m_inputMobile=m_inputMobile;
            [self.ui_tableView reloadData];
            [self getOperatorInfoWithMobile:_m_inputMobile];
        }
//    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger number = 2;
    return number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    if (section==0)
    {
        rows=1;
    }
    else if (section==1)
    {
        rows=2;
    }
    
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = nil;
    
    if (indexPath.section==0)
    {
        cell = [self trafficUserCell];
    }
    else if (indexPath.section==1)
    {
        if (indexPath.row==0)
        {
            cell = [self trafficUserNumberCell];
        }
        else if (indexPath.row==1)
        {
            cell = [self trafficUserDetailCell];
        }
    }
    
    return cell;
}

- (XHTrafficUserCell*)trafficUserCell
{
    XHTrafficUserCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHTrafficUserCellIdentifier];
    if (self.packageDic)
    {
        NSInteger values = [self.packageDic[@"productValue"] integerValue];
        NSString * unit = @"";
        NSInteger usedTime = [self.packageDic[@"usedTime"] integerValue];
        NSInteger remainTime = [self.packageDic[@"remainTime"] integerValue];
        NSInteger total = usedTime + remainTime;
        if (values>1000)
        {
            unit = @"G";
            values = values/1000;
        }
        else if (values<1000)
        {
            unit = @"M";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.ui_operator.text = [NSString stringWithFormat:@"%@",self.packageDic[@"operatorName"]];
        cell.ui_traffic.text = [NSString stringWithFormat:@"%ld%@",values,unit];
        cell.ui_useContent.text = [NSString stringWithFormat:@"使用情况%ld/%ld,还能用%ld次",usedTime,total,remainTime];
        cell.ui_realPrice.text = [NSString stringWithFormat:@"￥%@",self.packageDic[@"amount"]];
        cell.ui_originalPrice.text = [NSString stringWithFormat:@"￥%@",self.packageDic[@"productAmount"]];
        if ([self.packageDic[@"operatorName"] isEqualToString:@"中国移动"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#59A46C"];
        }
        else if ([self.packageDic[@"operatorName"] isEqualToString:@"中国电信"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#00AED2"];
        }
        else if ([self.packageDic[@"operatorName"] isEqualToString:@"中国联通"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#E45252"];
        }
    }
    else
    {
        NSInteger values = [self.trafficDic[@"productValue"] integerValue];
        NSString * unit = @"";
        if (values>1000)
        {
            unit = @"G";
            values = values/1000;
        }
        else if (values<1000)
        {
            unit = @"M";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.ui_operator.text = [NSString stringWithFormat:@"%@",self.trafficDic[@"operatorName"]];
        cell.ui_traffic.text = [NSString stringWithFormat:@"%ld%@",values,unit];
        cell.ui_useContent.text = [NSString stringWithFormat:@"使用情况%@/%@,还能用%@次",self.trafficDic[@"productCount"],self.trafficDic[@"originalCount"],self.trafficDic[@"originalCount"]];
        cell.ui_realPrice.text = [NSString stringWithFormat:@"￥%@",self.trafficDic[@"productPrice"]];
        cell.ui_originalPrice.text = [NSString stringWithFormat:@"￥%@",self.trafficDic[@"marketPrice"]];
        if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10086"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#59A46C"];
            cell.ui_operator.text = [NSString stringWithFormat:@"中国移动"];
        }
        else if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10000"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#00AED2"];
            cell.ui_operator.text = [NSString stringWithFormat:@"中国电信"];
        }
        else if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10010"])
        {
            cell.ui_bgView.backgroundColor = [ColorManager colorWithHexString:@"#E45252"];
            cell.ui_operator.text = [NSString stringWithFormat:@"中国联通"];
        }
    }

    return cell;
}
//输入号码
- (XHTrafficUserNumberCell*)trafficUserNumberCell
{
    XHTrafficUserNumberCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHTrafficUserNumberCellIdentifier];
    cell.ui_phoneTextField.tag = kPhoneNumberKey;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.ui_phoneTextField.delegate = self;
    cell.ui_phoneTextField.text = self.m_inputMobile;
    [cell.ui_phoneTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    if ([NSString checkNullString:self.m_inputMobile])
    {
        cell.ui_phoneTextField.text = @"";
    }
    else
    {
        if(self.m_inputMobile.length==11)
        {
            cell.ui_phoneTextField.text =[NSString stringWithFormat:@"%@ %@ %@",
                                          [self.m_inputMobile substringToIndex:3],
                                          [self.m_inputMobile substringWithRange:NSMakeRange(3,4)],
                                          [self.m_inputMobile substringFromIndex:7]];
        }
        else
        {
            cell.ui_phoneTextField.text =[NSString stringWithFormat:@"%@",self.m_inputMobile];
        }
    }
    
    return cell;
}
//选择数量
- (XHTrafficUserDetailCell*)trafficUserDetailCell
{
    XHTrafficUserDetailCell * cell = [self.ui_tableView dequeueReusableCellWithIdentifier:XHTrafficUserDetailCellIdentifier];
    
    cell.delegate = self;
    cell.ui_numberLabel.text = @"1";
    self.conut = cell.ui_numberLabel.text;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([NSString checkNullString:self.operatorName])
    {
        cell.ui_operator.text = @"";
    }
    else
    {
        cell.ui_operator.text = [NSString stringWithFormat:@"%@",self.operatorName];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=0;
    if (indexPath.section==0)
    {
        height = 100;
    }
    else if (indexPath.section==1)
    {
        if (indexPath.row==0)
        {
            height = 40;
        }
        else
        {
            height = 300;
        }
    }
    return height;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0.1;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    CGFloat height = 10;
    return height;
}

//#pragma mark - UITextFieldDelegate
//- (void)textFieldDidEndEditing:(UITextField *)textField
//{
//    self.m_inputMobile=textField.text;
//}

#pragma mark - UITextFieldDelegate
- (void)textFieldEditingChanged:(UITextField *)textField
{
    //限制手机账号长度（有两个空格）
    if (textField.text.length > 13) {
        textField.text = [textField.text substringToIndex:13];
    }
    
    NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
    
    NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *preStr = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //正在执行删除操作时为0，否则为1
    char editFlag = 0;
    if (currentStr.length <= preStr.length) {
        editFlag = 0;
    }
    else {
        editFlag = 1;
    }
    
    NSMutableString *tempStr = [NSMutableString new];
    
    int spaceCount = 0;
    if (currentStr.length < 3 && currentStr.length > -1) {
        spaceCount = 0;
    }else if (currentStr.length < 7 && currentStr.length > 2) {
        spaceCount = 1;
    }else if (currentStr.length < 12 && currentStr.length > 6) {
        spaceCount = 2;
    }
    
    for (int i = 0; i < spaceCount; i++) {
        if (i == 0) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
        }else if (i == 1) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
        }else if (i == 2) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
        }
    }
    
    if (currentStr.length == 11) {
        [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
    }
    if (currentStr.length < 4) {
        [tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
    }else if(currentStr.length > 3 && currentStr.length <12) {
        NSString *str = [currentStr substringFromIndex:3];
        [tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
        if (currentStr.length == 11) {
            [tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
        }
    }
    textField.text = tempStr;
    // 当前光标的偏移位置
    NSUInteger curTargetCursorPosition = targetCursorPosition;
    
    if (editFlag == 0) {
        //删除
        if (targetCursorPosition == 9 || targetCursorPosition == 4) {
            curTargetCursorPosition = targetCursorPosition - 1;
        }
    }else {
        //添加
        if (currentStr.length == 8 || currentStr.length == 4) {
            curTargetCursorPosition = targetCursorPosition + 1;
        }
    }
    UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;
    return YES;
}

#pragma mark - TextFieldNotification

- (void)textFieldTextDidChangesNotification:(NSNotification *)notif
{
    UITextField *textField=notif.object;
    if (textField.tag==kPhoneNumberKey&&[textField.text length]==13)
    {
        self.m_inputMobile=textField.text;
    }
}

#pragma - mark XHTrafficUserDetailCellDelegate 使用流量

- (void)useTrafficAction:(UIButton *)button
{
    //使用流量屯包
    if(self.packageDic)
    {
        if ([self.operatorName isEqualToString:self.packageDic[@"operatorName"]])
        {
            [ServiceManager getSubmitTokenSuccess:^(NSDictionary *data) {
                if ([data isKindOfClass:[NSString class]]) {
                    self.m_submitToken=(NSString *)data;
                    
                    if (![NSString checkNullString:self.m_inputMobile])
                    {
                        if ([self.m_inputMobile isEqualToString:[DataManager sharedInstance].userId])
                        {
                            //本机手机号
                            XHPaymentBouncedViewController * viewController = [[XHPaymentBouncedViewController alloc]init];
                            viewController.modalPresentationStyle = UIModalPresentationCustom;
                            viewController.phone = self.m_inputMobile;
                            viewController.conut = self.conut;
                            viewController.orderSn = self.packageDic[@"orderSn"];
                            viewController.phoneLocation = self.phoneLocation;
                            viewController.submitToken = self.m_submitToken;
                            [self presentViewController:viewController animated:NO completion:^{
                                
                            }];
                        }
                        else
                        {
                            //非本机
                            [PromptAction showWaitPrompt:@"加载中"];
                            [ServiceManager userTrafficPackageWithOrderSn:self.packageDic[@"orderSn"] userCount:self.conut phone:self.m_inputMobile passWord:@"" phoneLocation:self.phoneLocation submitToken:self.m_submitToken success:^(NSDictionary *data) {
                                [PromptAction dismissPrompt];
                                [PromptAction showSuccessPrompt:@"使用成功"];
                                [self.navigationController popViewControllerAnimated:YES];
                            } failure:^(NSDictionary *data) {
                                
                            }];
                        }
                    }
                    else
                    {
                        [PromptAction showInfoPrompt:@"请输入手机号"];
                    }
                }
            } failure:^(NSDictionary *data) {
                
            }];
        }
        else
        {
            [PromptAction showInfoPrompt:@"当前手机号码运营商无法使用该流量屯包"];
        }
    }
    else
    {
        //使用基金流量
        NSString * operatorName=@"";
        if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10086"])
        {
            operatorName = @"中国移动";
        }
        else if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10010"])
        {
            operatorName = @"中国联通";
        }
        else if ([self.trafficDic[@"operatorCode"] isEqualToString:@"10000"])
        {
            operatorName = @"中国电信";
        }
        if ([self.operatorName isEqualToString:operatorName])
        {
            if (![NSString checkNullString:self.m_inputMobile])
            {
                if ([self.m_inputMobile isEqualToString:[DataManager sharedInstance].userId])
                {
                    XHPaymentBouncedViewController * viewController = [[XHPaymentBouncedViewController alloc]init];
                    viewController.modalPresentationStyle = UIModalPresentationCustom;
                    viewController.phone = self.m_inputMobile;
                    viewController.conut = self.conut;
                    viewController.totalRemainCount = self.totalRemainCount;
                    viewController.fundProductId = self.trafficDic[@"sequenceNBR"];
                    viewController.phoneLocation = self.phoneLocation;
                    [self presentViewController:viewController animated:NO completion:^{
                        
                    }];
                }
                else
                {
                    [PromptAction showWaitPrompt:@"正在加载"];
                    [ServiceManager userFinancialBenefitsWithPhone:self.m_inputMobile phoneLocation:self.phoneLocation fundProductId:self.trafficDic[@"sequenceNBR"] chargeCount:self.conut success:^(NSDictionary *data) {
                        [PromptAction dismissPrompt];
                        [PromptAction showSuccessPrompt:@"使用成功"];
                        if ([self.conut integerValue]==self.totalRemainCount)
                        {
                            //全部使用完
                            AppDelegate * delegate = [UIApplication sharedApplication].delegate;
                            [delegate.tabBarController goMyMoneyFlow:1];
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }
                        else
                        {
                            //还有剩余
                            AppDelegate * delegate = [UIApplication sharedApplication].delegate;
                            [delegate.tabBarController goMyMoneyFlow:0];
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }
                    } failure:^(NSDictionary *data) {
                        
                    }];

                }
            }
            else
            {
                [PromptAction showInfoPrompt:@"请输入手机号"];
            }
        }
        else
        {
            [PromptAction showInfoPrompt:@"当前手机号码运营商无法使用该流量屯包"];
        }
    }
}

#pragma - mark XHTrafficUserDetailCellDelegate 选择数量

- (void)cell:(XHTrafficUserDetailCell *)cell addAction:(id)sender
{
    if (self.packageDic)
    {
        if (![self.conut isEqualToString:cell.ui_numberLabel.text])
        {
            self.conut=[NSString stringWithFormat:@"%@",cell.ui_numberLabel.text];
        }
        if ([cell.ui_numberLabel.text integerValue]+1<=[self.packageDic[@"remainTime"] integerValue])
        {
            cell.ui_numberLabel.text = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]+1];
            self.conut = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]];
            NSLog(@"%@",self.conut);
        }
        else
        {
            [PromptAction showInfoPrompt:@"已达上限"];
        }
    }
    else
    {
        if (![self.conut isEqualToString:cell.ui_numberLabel.text])
        {
            self.conut=[NSString stringWithFormat:@"%@",cell.ui_numberLabel.text];
        }
        if ([cell.ui_numberLabel.text integerValue]+1<=[self.trafficDic[@"productCount"] integerValue])
        {
            cell.ui_numberLabel.text = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]+1];
            self.conut = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]];
            NSLog(@"%@",self.conut);
        }
        else
        {
            [PromptAction showInfoPrompt:@"已达上限"];
        }
    }
}

- (void)cell:(XHTrafficUserDetailCell *)cell deleteAction:(id)sender
{
    if ([cell.ui_numberLabel.text integerValue]==1)
    {
        [PromptAction showInfoPrompt:@"已达下限"];
    }
    else
    {
        cell.ui_numberLabel.text = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]-1];
        self.conut = [NSString stringWithFormat:@"%ld",[cell.ui_numberLabel.text integerValue]];
        NSLog(@"%@",self.conut);
    }
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
#pragma - mark XHTrafficUserNumberCellDelegate 获取手机通讯录

- (void)addressBookAction:(UIButton *)button
{
    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    [peoplePicker setDisplayedProperties:@[@(kABPersonPhoneProperty)]];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:YES completion:nil];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    NSLog(@"%@",(__bridge NSString*)value);
    self.m_inputMobile=(__bridge NSString*)value;
}

#pragma clang diagnostic pop

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
